package auctionhaus

class Listing {
    String name
    Date dateCreated
    Date endTime
    boolean isComplete = false
    String description
    
    Customer seller
    Customer winner

    double startBid
    double minBid
    static hasMany = [bids: Bid]

    static constraints = {
        // make sure name can only be 64 chars and not blank
        name maxSize:  64, blank: false

        // make sure end time is not blank and is a date in the future
        endTime blank: false, validator: { valDate ->
            return valDate.after(new Date())
        }

        // make sure description is less than 256 chars and can be blank or null
        description maxSize: 256, blank: true, nullable: true

        // make sure the seller is not blank
        seller blank: false

        // make sure the winner can be nullable or blank since a listing may not have a winner yet
        winner blank: true, nullable: true

        // make sure it always has a starting bid
        startBid blank: false, validator: {
            it > 0.0
        }

        // make sure bids are at least .5 greater than previous
        bids validator: { incomingBids, instance ->
            if(instance.isComplete) {
                return false
            }
            else {
                def retVal = true
                incomingBids.each {
                    if(!it.dateCreated) {
                        it.dateCreated = new Date()
                    }
                }
                if(incomingBids) {
                    def allBids = incomingBids.sort {it.dateCreated}
                    /*
                    allBids.each {
                        println "Test: it = " + it.amount + ", created at " + it.dateCreated
                    }
                    */
                    double startBidValue = instance.startBid
                    //println "Debug: start bid = " + startBidValue
                    def previous = allBids[0]
                    if(previous.amount < startBidValue) {
                        retVal = false
                    }
                    else {
                        allBids.each {
                            if(it.id != previous.id) {
                                //println "Debug: it.amount = " + it.amount + ", previous.amount = " + previous.amount
                                if(it.amount < previous.amount + 0.5) {
                                    //println "Debug: returning false"
                                    retVal = false
                                }
                                previous = it
                            }
                        }
                    }
                }
                return retVal
            }
        }
    }
}
